#include <inttypes.h>
#include <avr/io.h>

#include "uart.h"


/**
 * Init function for USART0
 **/
void UARTInit(void)
{
  /* Baudrate = 9600 Baud, F_OSC = 4Mhz, U2X=0 (normal speed) => value for UBBR = 25 decimal , 0b0000 00011001
   * Formular for calculation on page 175, Examples of the most common UBBR Settings on pages 195ff
   * */
  UBRR0H = (unsigned char) 0; // 4 most significant bits of 25 = 0b0000 =0
  UBRR0L = (unsigned char)  51; // 8 least significant bits = 0b11001 = 25

  /* Enable receiver and transmitter and Receive interupt*/
  //UCSR0B = (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);
  UCSR0B = (1 << RXEN0) | (1 << TXEN0);

  /* Set frame format: 8data, 1stop bit 8N1
   * 0 << USBS0 = 1 stop bit
   * 1 << USBS0 = 2 stop bits (p.193)
   *
   * 3 << UCSZ00 = 8 data bits (p.193)
   * */
  UCSR0C = (0 << USBS0) | (3 << UCSZ00);
}


void UARTInitDynamic(int baud, char flags)
{
}

/**
 * Sends one char through USART0
 * \param char - the char to be send
 */
void UARTPutChar(char data)
{
  /* Wait for empty transmit buffer */
  while (!(UCSR0A & (1 << UDRE0)));
  /* Put data into buffer, sends the data */
  UDR0 = data;
}


unsigned char UARTGetChar(void)
{
  // while (!(UCSRA & (1<<RXC)));  // warten bis Zeichen verfuegbar
  //return UDR;                   // Zeichen aus UDR an Aufrufer zurueckgeben
  while (!(UCSR0A & (1<<RXC0)));  // warten bis Zeichen verfuegbar
    return UDR0;  
}

void UARTWrite(char* msg)
{
  while(*msg != '\0')
  {
     UARTPutChar (*msg++);
  }
}

unsigned char AsciiToHex(unsigned char high,unsigned char low)
{
  unsigned char new;

  // check if lower equal 9 ( ascii 57 )
  if(high <= 57) // high is a number
    high = high -48;
  else // high is a letter
    high = high -87;

  high = high << 4;
  high = high & 0xF0;
 
  // check if lower equal 9 ( ascii 57 )
  if(low <= 57) // high is a number
    low = low -48;
  else // high is a letter
    low = low -87;
  low = low & 0x0F;
 
  new = high | low;
 
  return new;
}

void SendHex(unsigned char hex)
{
  unsigned char high,low;
  // get highnibble
  high = hex & 0xF0;
  high = high >> 4;
 
  // get lownibble
  low = hex & 0x0F;
 
  if(high<=9)
    UARTPutChar(high+48);
  else
    UARTPutChar(high+87);
 
 
  if(low<=9)
    UARTPutChar(low+48);
  else
    UARTPutChar(low+87);

}

